package com.yangtao.prototype.master.dao;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.xwork.StringUtils;
import org.springframework.stereotype.Repository;
import org.springframework.util.Assert;

import com.yangtao.framework.constant.Option;
import com.yangtao.framework.constant.SysConstant;
import com.yangtao.framework.hibernate.BaseDao;
import com.yangtao.prototype.master.entity.Constant;

@Repository
public class ConstantDAO extends BaseDao<Constant> {
	/**
	 * 根据类型查询下拉单内容
	 * 
	 * @param types
	 *            类型
	 * @param userId
	 *            用户ID
	 * @param companyId
	 *            公司ID
	 * @return 下拉单内容
	 */
	public HashMap<String, List<Option>> getOptionList(String[] types,
			String userId) {
		Assert.notEmpty(types, "类型不能为空");
		HashMap<String, List<Option>> ret = new HashMap<String, List<Option>>();
		StringBuilder sql = new StringBuilder(
				"select new com.yangtao.framework.constant.Option(c.code,c.name) from Constant c where c.type=? and c.isDelete=?");
		if (StringUtils.isNotBlank(userId)) {
			sql.append(" and c.userId = '");
			sql.append(userId.trim());
			sql.append("'");
		}
		for (int i = 0; i < types.length; i++) {
			List<Option> lst = find(sql.toString(), types[i].trim(),
					com.yangtao.framework.constant.SysConstant.LOGIC_NO);
			ret.put(types[i], lst);
		}
		return ret;
	}

	public List<Option> getAllList(String companyId) {
		StringBuilder sql = new StringBuilder(
				"select distinct c.type,c.typeName from Constant c where c.isSystem=:isSystem");
		Map<String, Object> paraterMap = new HashMap<String, Object>();
		paraterMap.put("isSystem", SysConstant.LOGIC_NO);
		// if (StringHelper.isNotEmpty(companyId)) {
		// sql.append(" and c.companyId=:companyId");
		// paraterMap.put("companyId", companyId);
		// }
		List<Object[]> objs = find(sql.toString(), paraterMap);
		List<Option> ret = new ArrayList<Option>();
		for (Object[] obj : objs) {
			ret.add(new Option(obj[0].toString(), obj[1].toString()));
		}
		return ret;
	}

	public List<Constant> findByCode(String code) {
		return find("from Constant c where c.code like ?", code + "%");
	}
}
